//
//  ANSendMessageViewController.m
//  ANBlueTooth
//
//  Created by 王进盛 on 2017/12/3.
//  Copyright © 2017年 ania. All rights reserved.
//

#import "ANSendMessageViewController.h"
#import "Masonry.h"
#import "EasyBlueToothManager.h"
#import "EasyUtils.h"
#import "EFShowView.h"
#import "ToolInputView.h"
#import "ToolDetailViewController.h"
#import "EFShowView.h"
#import "ALCommon.h"
#import "AppDelegate.h"
#import "EasyUtils.h"

typedef enum {
    REVICE_TYPE_HEX =1,
    REVICE_TYPE_NO,
}REVICE_TYPE;

typedef enum {
    SEND_TYPE_HEX =1,
    SEND_TYPE_NO,
}SEND_TYPE;

typedef enum {
    SEND_RESPONE_RESPONE =1,
    SEND_RESPONE_NORESPONE,
}SEND_RESPONE;

#define mygreen [UIColor colorWithRed:172.0f/255.0f green:225.0f/255.0f blue:146.0f/255.0f alpha:1]

@interface ANSendMessageViewController (){
    
    UITextView * enterTextView ;
    UITextView * showTextView;
    
    UILabel *reivceValueLabel ;
    UILabel *revicePakgeLabel ;
    
    UILabel *sendValueLabel ;
    UILabel *sendPakgeLabel ;
    
    UITextField * msTextField;
    
    UIButton    * backButton;
    
    REVICE_TYPE  reviceType;
    SEND_TYPE    sendType;
    SEND_RESPONE sendResPone;
    
    NSMutableString * reviceString;
    NSMutableString * sendString;
    
    NSInteger   reviceByteNumber;
    NSInteger   revicePagkeNumber;
   
    NSInteger   sendByteNumber;
    NSInteger   sendPagkeNumber;
    
    NSTimer     *myTimer ;
    
    UInt64  oldInterVal;
    
    BOOL isAutoSend;
    
    BOOL isfrist;
    
    
}

@property (nonatomic,strong)EasyCenterManager  *centerManager ;

@property (nonatomic,strong)UIView *heardView;
@property (nonatomic,strong)UIView *showMessageView;
@property (nonatomic,strong)UIView *bottomView;


@end

@implementation ANSendMessageViewController

- (void)popToRootView
{
    [myTimer invalidate];
    myTimer =nil;
    

    
    [self.peripheral disconnectDevice];
    [AppDelegate appDelegate].currentCharacteristic = nil;
    [[AppDelegate appDelegate].currentNotiyCharacteristic removeAllObjects];
    [[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillShowNotification];
    [[NSNotificationCenter defaultCenter] removeObserver:UIKeyboardWillHideNotification];
 
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)dealloc
{
    //如果你想退出界面断开与设备的连接。就加上这句
//    [self.peripheral disconnectDevice];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = self.peripheral.name;
    reviceType = REVICE_TYPE_NO;
    sendType = SEND_TYPE_NO;
    sendResPone = SEND_RESPONE_NORESPONE;
    
    reviceByteNumber = 0;
    revicePagkeNumber = 0;
    sendByteNumber = 0;
    sendPagkeNumber = 0 ;
    
    isAutoSend = NO;
    isfrist = YES;
    
    oldInterVal =[[NSDate date] timeIntervalSince1970]*1000;
    
    reviceString = [NSMutableString string];
    sendString = [NSMutableString string];

    
    [self loadHeadViewUI];
    [self loadBottomViewUI];
    [self loadShowMessageViewUI];
    [enterTextView setText:@"1234567890"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                              selector:@selector(keyboardWillShow:)
                                                  name:UIKeyboardWillShowNotification
                                                object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    UITapGestureRecognizer *tag = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideView)];
    tag.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:tag];
    
//    myTimer =  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(rssiRead) userInfo:nil repeats:YES];
    
   
    kWeakSelf(self)
    
    self.centerManager.stateChangeCallback = ^(EasyCenterManager *manager, CBManagerState state) {
        [weakself managerStateChanged:state];
    };
    __block ANSendMessageViewController *weakSelf = self;
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5/*延迟执行时间*/ * NSEC_PER_SEC));
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [weakSelf showAlertView];
    });
    
    
    [self.peripheral discoverAllDeviceServiceWithCallback:^(EasyPeripheral *peripheral, NSArray<EasyService *> *serviceArray, NSError *error) {
        
        //        NSLog(@"%@  == %@",serviceArray,error);
        
        for (EasyService *tempS in serviceArray) {
            //            NSLog(@" %@  = %@",tempS.UUID ,tempS.description);
            
            [tempS discoverCharacteristicWithCallback:^(NSArray<EasyCharacteristic *> *characteristics, NSError *error) {
//                                NSLog(@" ++++++++++++++++++%@  = %@",characteristics , error );
                
                for (EasyCharacteristic *tempC in characteristics) {
                    [tempC discoverDescriptorWithCallback:^(NSArray<EasyDescriptor *> *descriptorArray, NSError *error) {
                        //                        NSLog(@"%@ ====", descriptorArray)  ;
                        //                        if (descriptorArray.count > 0) {
                        //                            for (EasyDescriptor *d in descriptorArray) {
                        //                                NSLog(@"%@ - %@ %@ ", d,d.UUID ,d.value);
                        //                            }
                        //                        }
//                        for (EasyDescriptor *desc in descriptorArray) {
//                            [desc readValueWithCallback:^(EasyDescriptor *descriptor, NSError *error) {
//                                //                                NSLog(@"读取descriptor的值：%@ ,%@ ",descriptor.value,error);
//                            }];
//                        }
                        queueMainStart
                        [EFShowView HideHud];
              
                        queueEnd
                    }];
                    //开启默认的监听
                    NSArray *array  = [tempC.propertiesString componentsSeparatedByString:@" "];
                    NSArray *characArray = [NSMutableArray arrayWithArray:array];
                   
                    if ([characArray containsObject:@"Write"]||[characArray containsObject:@"WriteWithoutResponse"]) {
                        if ([characArray containsObject:@"WriteWithoutResponse"]) {
                            [AppDelegate appDelegate].currentCharacteristic = tempC;
                        }else{
                            if (![AppDelegate appDelegate].currentCharacteristic) {
                                [AppDelegate appDelegate].currentCharacteristic = tempC;
                            }
                        }
                    }else if ([characArray containsObject:@"Read"]||[characArray containsObject:@"Notify"]||[characArray containsObject:@"Indicate"]){
                        if ([characArray containsObject:@"Notify"]) {
                            [tempC notifyWithValue:!tempC.isNotifying callback:^(EasyCharacteristic *characteristic, NSData *data, NSError *error) {
                                if (isfrist) {
                                    isfrist = NO;
                                    return ;
                                }
                                NSLog(@"监听开启是否有数据%@,%@",data,tempC.UUID);
                                queueMainStart
                                [NSObject cancelPreviousPerformRequestsWithTarget:self];
                                queueEnd
                                revicePagkeNumber++;
                                reviceByteNumber +=data.length;
                                if (!data) {
                                    return ;
                                }
                                switch (reviceType) {
                                    case REVICE_TYPE_NO:
                                    {
                                        NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF16StringEncoding];
                                        [reviceString appendFormat:@"%@\n",dataString];
                                    }
                                        break;
                                    case REVICE_TYPE_HEX:
                                    {
                                        [reviceString appendFormat:@"%@\n",[data description]];
                                    }
                                    default:
                                        break;
                                }
                                UInt64 msecond2 = [[NSDate date] timeIntervalSince1970]*1000;
                                NSLog(@"%llu,,,%llu",msecond2-oldInterVal ,msecond2);
                                if (msecond2-oldInterVal >400) {
                                    oldInterVal = msecond2;
                                    queueMainStart
                                    NSLog(@"shuju=%@",reviceString);
                                    [showTextView setText: reviceString];
                                    [revicePakgeLabel setText:[NSString stringWithFormat:@"%ld",revicePagkeNumber]];
                                    [reivceValueLabel setText:[NSString stringWithFormat:@"%ld",reviceByteNumber]];
                                    [showTextView scrollRectToVisible:CGRectMake(0, showTextView.contentSize.height-15, showTextView.contentSize.width, 10) animated:YES];
                                    queueEnd
                                }else{
                                    queueMainStart
                                    [self performSelector:@selector(checkMessageIsEnd) withObject:nil afterDelay:0.1];
                                    queueEnd
                                }
                            }];
                            
                            [tempC readValueWithCallback:^(EasyCharacteristic *characteristic, NSData *data, NSError *error) {
                                queueMainStart
                                [NSObject cancelPreviousPerformRequestsWithTarget:self];
                                queueEnd
                                revicePagkeNumber++;
                                reviceByteNumber +=data.length;
                                if (!data) {
                                    return ;
                                }
                                switch (reviceType) {
                                    case REVICE_TYPE_NO:
                                    {
                                        NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                        [reviceString appendFormat:@"%@\n",dataString];
                                    }
                                        break;
                                    case REVICE_TYPE_HEX:
                                    {
                                        [reviceString appendFormat:@"%@\n",[data description]];
                                    }
                                    default:
                                        break;
                                }
                                UInt64 msecond2 = [[NSDate date] timeIntervalSince1970]*1000;
                                NSLog(@"%llu,,,%llu",msecond2-oldInterVal ,msecond2);
                                if (msecond2-oldInterVal >400) {
                                    oldInterVal = msecond2;
                                    queueMainStart
                                    NSLog(@"shuju=%@",reviceString);
                                    [showTextView setText: reviceString];
                                    [revicePakgeLabel setText:[NSString stringWithFormat:@"%ld",revicePagkeNumber]];
                                    [reivceValueLabel setText:[NSString stringWithFormat:@"%ld",reviceByteNumber]];
                                    [showTextView scrollRectToVisible:CGRectMake(0, showTextView.contentSize.height-15, showTextView.contentSize.width, 10) animated:YES];
                                    queueEnd
                                }else{
                                    queueMainStart
                                    [self performSelector:@selector(checkMessageIsEnd) withObject:nil afterDelay:0.1];
                                    queueEnd
                                }
                            }];
                            
                            [[AppDelegate appDelegate].currentNotiyCharacteristic addObject:tempC];
                        }
                        
                   
                    }
                }
            }];
        }
    }];
    
}

- (void)rssiRead {
    [self.peripheral readDeviceRSSIWithCallback:^(EasyPeripheral *peripheral, NSNumber *RSSI, NSError *error) {
//        self.navigationItem.rightBarButtonItem.title = [RSSI description];
        queueMainStart
        [self loadRightButtonItem:RSSI];
        queueEnd
    }];
}

- (void)loadRightButtonItem:(NSNumber*)rssi{
    backButton  = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setFrame:CGRectMake(0, 0, 40, 40)];
    [backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [backButton setTitle:[rssi description] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(popToRootView) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
}

- (void)showAlertView {
    
    [EFShowView showHUDMsg:@"获取服务..." ];
     __block ANSendMessageViewController *weakSelf = self;
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2/*延迟执行时间*/ * NSEC_PER_SEC));
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        [weakSelf hideAlertView];
    });
}
- (void)hideAlertView {
    [EFShowView HideHud];
}

#pragma mark - bluetooth callback

- (void)managerStateChanged:(CBManagerState)state
{
    queueMainStart
    if (state == CBManagerStatePoweredOn) {
        UIView *coverView = [[UIApplication sharedApplication].keyWindow viewWithTag:1011];
        if (coverView) {
            [coverView removeFromSuperview];
            coverView = nil ;
        }
        
        UIViewController *vc = [EasyUtils topViewController];
        if ([vc isKindOfClass:[self class]]) {
            [self.centerManager startScanDevice];
        }
        
    }
    else if (state == CBManagerStatePoweredOff){
        UILabel *coverLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        coverLabel.font = [UIFont systemFontOfSize:20];
        coverLabel.tag = 1011 ;
        coverLabel.textAlignment = NSTextAlignmentCenter ;
        coverLabel.text = @"系统蓝牙已关闭，请打开系统蓝牙";
        coverLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        [[UIApplication sharedApplication].keyWindow addSubview:coverLabel];
    }
    queueEnd
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)hideView {
    [self.view endEditing:YES];
}

- (void)keyboardWillShow:(NSNotification*)notification{
    CGRect keyboardFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"%@", NSStringFromCGRect(keyboardFrame));
    
    CGFloat ory = keyboardFrame.origin.y-_bottomView.frame.size.height;
    [_bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(self.view).offset(ory);
        make.height.equalTo(self.view.mas_height).multipliedBy(0.3);
    }];
}

- (void)keyboardWillHide:(NSNotification*)notification{
    
    [_bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.bottom.trailing.equalTo(self.view);
        make.height.equalTo(self.view.mas_height).multipliedBy(0.3);
    }];
}

- (void)loadHeadViewUI
{
    _heardView = [[UIView alloc] init];
    _heardView.backgroundColor = mygreen;
    [self.view addSubview:_heardView];
    
    [_heardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.trailing.equalTo(self.view);
        make.height.mas_equalTo(@114);
    }];
    
    UILabel *hexLabel = [[UILabel alloc] init];
    hexLabel.text = @"Hex接收";
    hexLabel.font = [UIFont systemFontOfSize:14];
    [_heardView addSubview:hexLabel];
    
    [hexLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(_heardView);
        make.bottom.equalTo(_heardView).offset(-15);
    }];
    
    UISwitch * hexSwitch = [[UISwitch alloc] init];
    [_heardView addSubview:hexSwitch];
    [hexSwitch addTarget:self action:@selector(hexReviceType:) forControlEvents:UIControlEventValueChanged];
    
    [hexSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(hexLabel.mas_trailing);
        make.bottom.equalTo(_heardView).offset(-8);
    }];
    
    UIButton  *serviceButton = [[UIButton alloc] init];
    [serviceButton setTitle:@"选择服务" forState:UIControlStateNormal];
    serviceButton.layer.cornerRadius = 4;
    serviceButton.backgroundColor = [UIColor colorWithRed:126.0f/255.0f green:212/255.0f blue:211/255.0f alpha:1];
    [_heardView addSubview:serviceButton];
    
    [serviceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_heardView);
        make.bottom.equalTo(_heardView).offset(-8);
    }];
    
    [serviceButton addTarget:self action:@selector(enterService) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton  *clearButton = [[UIButton alloc] init];
    [clearButton setTitle:@"清空数据" forState:UIControlStateNormal];
    clearButton.layer.cornerRadius = 4;
    clearButton.backgroundColor =  [UIColor colorWithRed:126.0f/255.0f green:212/255.0f blue:211/255.0f alpha:1];
    [_heardView addSubview:clearButton];
    
    [clearButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(_heardView).offset(-10);
        make.bottom.equalTo(_heardView).offset(-8);
    }];
    
    [clearButton addTarget:self action:@selector(clearMessageEvent) forControlEvents:UIControlEventTouchUpInside];
}

- (void)loadShowMessageViewUI {
    _showMessageView = [[UIView alloc] init];
    [self.view addSubview:_showMessageView];
    [_showMessageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(_heardView.mas_bottom);
        make.bottom.equalTo(_bottomView.mas_top);
    }];
    
    showTextView = [[UITextView alloc] init];
    showTextView.editable = NO;
    showTextView.layer.cornerRadius = 5.0F;
    showTextView.layer.borderWidth = 3;
    showTextView.layer.borderColor = [UIColor colorWithRed:172.0f/255.0f green:225.0f/255.0f blue:146.0f/255.0f alpha:1].CGColor;
    showTextView.keyboardType = UIKeyboardTypeASCIICapable;
    [showTextView scrollRectToVisible:CGRectMake(0, showTextView.contentSize.height-15, showTextView.contentSize.width, 10) animated:YES];
    [_showMessageView addSubview:showTextView];
    
    [showTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(_showMessageView);
        make.top.equalTo(_showMessageView).offset(20);
        make.bottom.equalTo(_showMessageView).offset(-20);
    }];
    
    UILabel *reviceNoticeLabel = [[UILabel alloc] init];
    reviceNoticeLabel.font = [UIFont systemFontOfSize:14];
    reviceNoticeLabel.text = @"接收:";
    reviceNoticeLabel.textColor = mygreen;
    [_showMessageView addSubview:reviceNoticeLabel];
    [reviceNoticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(_showMessageView).offset(10);
        make.top.equalTo(_showMessageView);
        make.width.mas_equalTo(@35);
    }];
    
    reivceValueLabel = [[UILabel alloc] init];
    reivceValueLabel.font = [UIFont systemFontOfSize:14];
    reivceValueLabel.text = @"0";
    [_showMessageView addSubview:reivceValueLabel];
    [reivceValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(reviceNoticeLabel.mas_trailing);
        make.top.equalTo(reviceNoticeLabel);
    }];
    
    UILabel *reviceByteNoticeLabel = [[UILabel alloc] init];
    reviceByteNoticeLabel.font = [UIFont systemFontOfSize:14];
    reviceByteNoticeLabel.textColor = mygreen;
    reviceByteNoticeLabel.text = @"字节";
    [_showMessageView addSubview:reviceByteNoticeLabel];
    [reviceByteNoticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(reivceValueLabel.mas_trailing);
        make.top.equalTo(_showMessageView);
    }];
    
    revicePakgeLabel = [[UILabel alloc] init];
    revicePakgeLabel.font = [UIFont systemFontOfSize:14];
    revicePakgeLabel.text = @"0";
    [_showMessageView addSubview:revicePakgeLabel];
    [revicePakgeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(reviceByteNoticeLabel.mas_trailing).offset(5);
        make.top.equalTo(_showMessageView);
    }];
    
    UILabel *revicePagkeNoticeLabel = [[UILabel alloc] init];
    revicePagkeNoticeLabel.font = [UIFont systemFontOfSize:14];
    revicePagkeNoticeLabel.textColor = mygreen;
    revicePagkeNoticeLabel.text = @"包";
    [_showMessageView addSubview:revicePagkeNoticeLabel];
    [revicePagkeNoticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(revicePakgeLabel.mas_trailing);
        make.top.equalTo(_showMessageView);
    }];
    
    //////发送
    UILabel *sendNoticeLabel = [[UILabel alloc] init];
    sendNoticeLabel.font = [UIFont systemFontOfSize:14];
    sendNoticeLabel.text = @"发送:";
    sendNoticeLabel.textColor = mygreen;
    [_showMessageView addSubview:sendNoticeLabel];
    [sendNoticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(_showMessageView).offset(10);
        make.bottom.equalTo(_showMessageView);
        make.width.mas_equalTo(@35);
    }];
    
    sendValueLabel = [[UILabel alloc] init];
    sendValueLabel.font = [UIFont systemFontOfSize:14];
    sendValueLabel.text = @"0";
    [_showMessageView addSubview:sendValueLabel];
    [sendValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(sendNoticeLabel.mas_trailing);
        make.bottom.equalTo(sendNoticeLabel);
    }];
    
    UILabel *sendByteNoticeLabel = [[UILabel alloc] init];
    sendByteNoticeLabel.font = [UIFont systemFontOfSize:14];
    sendByteNoticeLabel.textColor = mygreen;
    sendByteNoticeLabel.text = @"字节";
    [_showMessageView addSubview:sendByteNoticeLabel];
    [sendByteNoticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(sendValueLabel.mas_trailing);
        make.bottom.equalTo(_showMessageView);
    }];
    
    sendPakgeLabel = [[UILabel alloc] init];
    sendPakgeLabel.font = [UIFont systemFontOfSize:14];
    sendPakgeLabel.text = @"0";
    [_showMessageView addSubview:sendPakgeLabel];
    [sendPakgeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(sendByteNoticeLabel.mas_trailing).offset(5);
        make.bottom.equalTo(_showMessageView);
    }];
    
    UILabel *sendPagkeNoticeLabel = [[UILabel alloc] init];
    sendPagkeNoticeLabel.font = [UIFont systemFontOfSize:14];
    sendPagkeNoticeLabel.textColor = mygreen;
    sendPagkeNoticeLabel.text = @"包";
    [_showMessageView addSubview:sendPagkeNoticeLabel];
    [sendPagkeNoticeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(sendPakgeLabel.mas_trailing);
        make.bottom.equalTo(_showMessageView);
    }];
    
}

- (void)loadBottomViewUI {
    _bottomView = [[UIView alloc] init];
    _bottomView.backgroundColor = [UIColor colorWithRed:172.0f/255.0f green:225.0f/255.0f blue:146.0f/255.0f alpha:1];
    [self.view addSubview:_bottomView];
    [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.bottom.trailing.equalTo(self.view);
        make.height.equalTo(self.view.mas_height).multipliedBy(0.28);
    }];
    
    enterTextView = [[UITextView alloc] init];
    enterTextView.layer.cornerRadius = 5.0F;
    enterTextView.layer.borderWidth = 3;
    enterTextView.layer.borderColor = [UIColor whiteColor].CGColor;
    enterTextView.keyboardType = UIKeyboardTypeASCIICapable;
    [_bottomView addSubview:enterTextView];
    
    [enterTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.equalTo(_bottomView).offset(10);
        make.trailing.equalTo(_bottomView).offset(-10);
        make.height.equalTo(_bottomView.mas_height).multipliedBy(0.5);
    }];
    
    msTextField = [[UITextField alloc] init];
    msTextField.backgroundColor = [UIColor whiteColor];
    msTextField.layer.cornerRadius = 3;
    msTextField.keyboardType = UIKeyboardTypeASCIICapable;
    msTextField.text = @"100";
    [_bottomView addSubview:msTextField];
    
    [msTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(_bottomView).offset(10);
        make.top.equalTo(enterTextView.mas_bottom).offset(5);
        make.width.mas_equalTo(@100);
        make.height.mas_equalTo(@30);
    }];
    
    UILabel * msLabel = [[UILabel alloc] init];
    msLabel.text = @"ms";
    [_bottomView addSubview:msLabel];

    [msLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(msTextField);
        make.leading.equalTo(msTextField.mas_trailing);
    }];
    
    UILabel *timeSendLabel = [[UILabel alloc] init];
    timeSendLabel.text = @"定时发送";
    timeSendLabel.font = [UIFont systemFontOfSize:14];
    [_bottomView addSubview:timeSendLabel];
    
    [timeSendLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(msTextField);
        make.leading.equalTo(msLabel.mas_trailing).offset(10);
    }];
    
    UISwitch * sendSwitch = [[UISwitch alloc] init];
    [_bottomView addSubview:sendSwitch];
    [sendSwitch addTarget:self action:@selector(timeSend:) forControlEvents:UIControlEventValueChanged];
    
    
    [sendSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(msTextField);
        make.leading.equalTo(timeSendLabel.mas_trailing);
    }];
    
    UILabel *hexSendLabel = [[UILabel alloc] init];
    hexSendLabel.text = @"Hex发送";
    hexSendLabel.font = [UIFont systemFontOfSize:14];
    [_bottomView addSubview:hexSendLabel];
    
    [hexSendLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(_bottomView).offset(10);
        make.bottom.equalTo(_bottomView).offset(-8);
    }];

    UISwitch * HexSendSwitch = [[UISwitch alloc] init];
    [_bottomView addSubview:HexSendSwitch];
    [HexSendSwitch addTarget:self action:@selector(hexSendType:) forControlEvents:UIControlEventValueChanged];
    

    [HexSendSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(hexSendLabel);
        make.leading.equalTo(hexSendLabel.mas_trailing);
    }];
    
    UILabel *resSendLabel = [[UILabel alloc] init];
    resSendLabel.text = @"Response";
    resSendLabel.font = [UIFont systemFontOfSize:14];
    [_bottomView addSubview:resSendLabel];

    [resSendLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(hexSendLabel);
        make.leading.equalTo(HexSendSwitch.mas_trailing).offset(10);
    }];

    UISwitch * RessendSwitch = [[UISwitch alloc] init];
    [_bottomView addSubview:RessendSwitch];
    [RessendSwitch addTarget:self action:@selector(responseType:) forControlEvents:UIControlEventValueChanged];

    [RessendSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(hexSendLabel);
        make.leading.equalTo(resSendLabel.mas_trailing);
    }];
    
    UIButton  *sendButton = [[UIButton alloc] init];
    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    sendButton.layer.cornerRadius = 4;
    sendButton.backgroundColor = [UIColor colorWithRed:126.0f/255.0f green:212/255.0f blue:211/255.0f alpha:1];
    [_bottomView addSubview:sendButton];
    
    [sendButton addTarget:self action:@selector(sendMessageEvent) forControlEvents:UIControlEventTouchUpInside];
    
    [sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(_bottomView).offset(-10);
        make.top.equalTo(enterTextView.mas_bottom).offset(10);
        make.width.mas_equalTo(@60);
    }];
    
    
//    UIButton  *clearButton = [[UIButton alloc] init];
//    [clearButton setTitle:@"清空数据" forState:UIControlStateNormal];
//    clearButton.layer.cornerRadius = 4;
//    clearButton.backgroundColor = [UIColor lightGrayColor];
//    [_heardView addSubview:clearButton];
//
//    [clearButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.trailing.equalTo(_heardView).offset(-10);
//        make.bottom.equalTo(_heardView).offset(-8);
//    }];
}

- (void)enterService {
    [self.centerManager stopScanDevice];
    
    kWeakSelf(self)
    EasyPeripheral *peripheral = self.peripheral;
    if (peripheral.state==CBPeripheralStateConnected) {
        ToolDetailViewController *tooD = [[ToolDetailViewController alloc]init];
        tooD.peripheral = peripheral ;
        [weakself.navigationController pushViewController:tooD animated:YES];
    }
    else{
        [EFShowView showAlertMessageWithTitle:@"设备失去连接" contentMessage:nil cancelTitle:nil cancelCallBack:^{
            //重新连接设备
            [peripheral reconnectDevice];
        } sureTitle:@"取消" sureCallBack:^{
            [weakself.navigationController popToRootViewControllerAnimated:YES];
        }];
    }
}

#pragma --mark 清除所有数据
- (void)clearMessageEvent {
    [showTextView setText:@""];
    [revicePakgeLabel setText:@"0"];
    [reivceValueLabel setText:@"0"];
    [sendPakgeLabel setText:@"0"];
    [sendValueLabel setText:@"0"];
    reviceString = [NSMutableString string];
    
    reviceByteNumber = 0 ;
    revicePagkeNumber = 0;
    sendByteNumber = 0 ;
    sendPagkeNumber = 0;
}

#pragma --mark hex 设置
- (void)hexReviceType:(UISwitch *)sw{
    if (sw.isOn) {
        reviceType = REVICE_TYPE_HEX;
    }else{
        reviceType = REVICE_TYPE_NO;
    }
}

#pragma  --mark hex发送
- (void)hexSendType:(UISwitch *)sw {
    if (sw.isOn) {
        sendType = SEND_TYPE_HEX;
    }else{
        sendType = SEND_TYPE_NO;
    }
}

- (void)responseType:(UISwitch *)sw {
    if (sw.isOn) {
        sendResPone = SEND_RESPONE_RESPONE;
    }else{
        sendResPone = SEND_RESPONE_NORESPONE;
    }
}

- (void)timeSend:(UISwitch *)sw {
    if (sw.isOn) {
        //判断是否有值
        
        isAutoSend = YES;
        [self sendMessageEvent];
        [msTextField setEnabled:NO];
    }else{
        isAutoSend = NO;
         [msTextField setEnabled:YES];
    }
}

- (void)timerFired:(NSTimer *)time {
    [self sendMessageEvent];
}

- (void)sendMessageEvent {
    
    if (![AppDelegate appDelegate].currentCharacteristic.UUID) {
        [ALCommon showPromptMessageInPoint:self.view.center text:@"蓝牙初始化错误" duration:2];
        [self popToRootView];
        return;
    }
    
    
    NSString  * enterStirng = enterTextView.text;
    
    if (!enterStirng.length) {
        //数据为空
        return;
    }
    
    NSData * data = [enterStirng dataUsingEncoding:NSUTF8StringEncoding];;
    switch (sendType) {
        case SEND_TYPE_NO:
        {
            data = [enterStirng dataUsingEncoding:NSUTF8StringEncoding];
        }
            break;
        case SEND_TYPE_HEX:
        {
            if (enterStirng.length %2) {
                [ALCommon showPromptMessageInPoint:self.view.center text:@"数据不能为单数" duration:2];
                return;
            }
     
            data =  [self nsdataFromHexString:enterStirng];
  
        }
        default:
            break;
    }
    sendByteNumber +=data.length;
    sendPagkeNumber ++;
    [sendPakgeLabel setText:[NSString stringWithFormat:@"%ld",sendPagkeNumber]];
    [sendValueLabel setText:[NSString stringWithFormat:@"%ld",sendByteNumber]];
    
    CBCharacteristicWriteType writeType;
    switch (sendResPone) {
        case SEND_RESPONE_RESPONE:
        {
            writeType =  CBCharacteristicWriteWithResponse;
        }
            break;
        case SEND_RESPONE_NORESPONE:
        {
            writeType =  CBCharacteristicWriteWithoutResponse;
        }
            break;
        default:
            break;
    }
    
    int count  = 0 ;
    
    if (data.length%20) {
        count = data.length/20+1;
    }else{
        count = data.length/20;
    }
    
    for (int i =0; i <count; i++) {
        NSData *data1;
        
        if (data.length<20) {
            data1 = [data subdataWithRange:NSMakeRange(i*20, data.length)];
        }else{
            if ((i+1)*20>data.length) {
                data1 = [data subdataWithRange:NSMakeRange(i*20, data.length-i*20)];
            }else{
                data1 = [data subdataWithRange:NSMakeRange(i, 20)];
            }
        }
        NSLog(@"data1 = %d,%d,%@",i*20, data.length-i*20,data1);
        [[AppDelegate appDelegate].currentCharacteristic writeValueWithData:data1 sendType:writeType callback:^(EasyCharacteristic *characteristic, NSData *data, NSError *error) {
            kWeakSelf(self)
            queueMainStart
            
            queueEnd
        }];
    }
    
    if (isAutoSend) {
        CGFloat ftime = [msTextField.text intValue]/1000.0;
        [self performSelector:@selector(sendMessageEvent) withObject:nil afterDelay:ftime];
    }

}

#pragma --check  查看数据是否完整
- (void)checkMessageIsEnd{
    [showTextView setText: reviceString];
    [revicePakgeLabel setText:[NSString stringWithFormat:@"%ld",revicePagkeNumber]];
    [reivceValueLabel setText:[NSString stringWithFormat:@"%ld",reviceByteNumber]];
    [showTextView scrollRectToVisible:CGRectMake(0, showTextView.contentSize.height-15, showTextView.contentSize.width, 10) animated:YES];
    
}


- (Byte)getByte:(NSString *)chatStrig {
    Byte a =strtoul([chatStrig UTF8String], 0, 16);
    return a;
}

// 十六进制转换为普通字符串的。
- (NSData *)nsdataFromHexString:(NSString *)hexString { //
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSString  * tempstring = [NSString stringWithFormat:@"0x%@",hexCharStr];
        NSInteger       one =  strtoul([tempstring UTF8String], 0, 16);
        myBuffer[i / 2] = (char)one;
    }
//    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    NSData *ldata = [NSData dataWithBytes:myBuffer length:hexString.length/2];
    NSLog(@"------字符串=======%@",ldata);
    return ldata;
    
    
}

//普通字符串转换为十六进制的。

- (NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}

@end
